package k8s

import (
	"k8s.io/client-go/rest"
	"k8s.io/apimachinery/pkg/apis/meta/v1"
	"fmt"
	"io/ioutil"
	"strings"
	"log"
	"k8s.io/apimachinery/pkg/util/yaml"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"io"
	"k8s.io/client-go/dynamic"
	"k8s.io/apimachinery/pkg/runtime/schema"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func DeleteResource(ns,resourceName,resourceType string) error {

	fmt.Println(ns,resourceName,resourceType)

	defaultPropagationPolicy := v1.DeletePropagationForeground
	defaultDeleteOptions := &v1.DeleteOptions{
		PropagationPolicy: &defaultPropagationPolicy,
	}

	var client rest.Interface
	switch resourceType {
	case "pods","services","configmaps","daemonsets","persistentvolumes","persistentvolumeclaims","secrets":
		client = clientset.CoreV1().RESTClient()
	case "deployments","replicasets","statefulsets":
		client = clientset.AppsV1().RESTClient()
	case "jobs":
		client = clientset.BatchV1().RESTClient()
	case "clusterroles":
		client = clientset.RbacV1().RESTClient()
	case "horizontalpodautoscalers":
		client = clientset.AutoscalingV1().RESTClient()
	}

	req := client.Delete().Resource(resourceType).Namespace(ns).Name(resourceName).Body(defaultDeleteOptions)

	return req.Do().Error()
}

func GetResource(ns,resourceName,resourceType string) (string,error) {

	fmt.Println(ns,resourceName,resourceType)

	var client rest.Interface
	switch resourceType {
	case "pods","services","configmaps","persistentvolumes","persistentvolumeclaims","secrets":
		client = clientset.CoreV1().RESTClient()
	case "deployments","replicasets","statefulsets","daemonsets":
		client = clientset.AppsV1().RESTClient()
	case "jobs":
		client = clientset.BatchV1().RESTClient()
	case "clusterroles":
		client = clientset.RbacV1().RESTClient()
	case "horizontalpodautoscalers":
		client = clientset.AutoscalingV1().RESTClient()
	}

	req := client.Get().Resource(resourceType).Namespace(ns).Name(resourceName)

	result,err := req.Do().Raw()
	if err != nil {
		fmt.Println(err.Error())
	}
	return string(result),err
}

func PutResource(ns,resourceName,resourceType string,payload []byte) (error) {

	fmt.Println(ns,resourceName,resourceType)

	var client rest.Interface
	switch resourceType {
	case "pods","services","configmaps","persistentvolumes","persistentvolumeclaims","secrets":
		client = clientset.CoreV1().RESTClient()
	case "deployments","replicasets","statefulsets","daemonsets":
		client = clientset.AppsV1().RESTClient()
	case "jobs":
		client = clientset.BatchV1().RESTClient()
	case "clusterroles":
		client = clientset.RbacV1().RESTClient()
	case "horizontalpodautoscalers":
		client = clientset.AutoscalingV1().RESTClient()
	}

	req := client.Put().
		Namespace(ns).
		Name(resourceName).
		Resource(resourceType).
		SetHeader("Content-Type", "application/json").
		Body(payload)


	return req.Do().Error()
}

func DeployAppFromFile(yamlPath string)  (err error) {
	resouceContent,err := ioutil.ReadFile(yamlPath)
	if err != nil {
		log.Println(err)
		return
	}else {
		//log.Println(strings.TrimSpace(string(status)))
		//模板渲染成镜像
		err = deployAppFromFile(strings.TrimSpace(string(resouceContent)))
	}
	return
}


func deployAppFromFile(content string) (err error) {
	reader := strings.NewReader(content)
	d := yaml.NewYAMLOrJSONDecoder(reader, 4096)

		data := unstructured.Unstructured{}
		if err = d.Decode(&data); err != nil {
			if err == io.EOF {
				//return true, nil
			}
			log.Println(err)
			return  err
		}

		version := data.GetAPIVersion()
		kind := data.GetKind()

		gv, err := schema.ParseGroupVersion(version)
		if err != nil {
			gv = schema.GroupVersion{Version: version}
		}

		dynamicClient, err := dynamic.NewForConfig(DynamicConfig)
		if err != nil {
			return  err
		}

		groupVersionResource := schema.GroupVersionResource{Group: gv.Group, Version: gv.Version, Resource: fmt.Sprintf("%s%s",strings.ToLower(kind),"s")}

		_, err = dynamicClient.Resource(groupVersionResource).Namespace(data.GetNamespace()).Create(&data, metav1.CreateOptions{})  //第N次构建怎么办？
		if err != nil {
			log.Println(err)
			return
		}
	return
}


